/* Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
  <file> getch.c </file>
  <brief>
    testing char-stream from uls input source.
    This file is part of ULS, Unified Lexical Scheme.
  </brief>
  <author>
    Stanley J. Hong <babel96@gmail.com>, 2011.
  </author>
*/

#include "uls.h"
#include "sample_lex.h"

#include <unistd.h>
#include <fcntl.h>

char *progname;
int  opt_verbose;
int  test_stage;

char *config_name;
char *input_file;
uls_lex_t *sample_lex;

static void usage(void)
{
	err_log("usage(%s):", progname);
	err_log("\t%s ", progname);
	exit(1);
}

static int
options(int opt, char* optarg)
{
	switch (opt) {
	case 'c':
		config_name = optarg;
		break;

	case 's':
		test_stage = atoi(optarg);
		break;

	case 'v':
		opt_verbose = 1;
		break;

	case 'h':
		usage();
		break;

	default:
		err_log("undefined option -%c", opt);
		return -1;
		break;
	}

	return 0;
}

static int
parse_options(int argc, char* argv[])
{
	int   opt;

	while ((opt=getopt(argc, argv, "c:svh")) != -1) {
		switch (opt) {
		case 'c':
			config_name = optarg;
			break;
	
		case 's':
			test_stage = atoi(optarg);
			break;
	
		case 'v':
			opt_verbose = 1;
			break;
	
		case 'h':
			usage();
			break;
	
		default:
			err_log("undefined option -%c", opt);
			return -1;
			break;
		}
	}

	return optind;
}

int
main(int argc, char* argv[])
{
	int i0;
	char ch, *fpath;
	int tok_id;

	progname = uls_filename(argv[0]);
	config_name = "sample.ulc";

	if ((i0=parse_options(argc, argv)) <= 0 || i0 >= argc) {
		usage();
		return -1;
	}

	fpath = argv[i0];

	if ((sample_lex = uls_create(config_name)) == NULL) {
		err_log("can't create uls-lexer");
		return -1;
	}

	uls_set_file(sample_lex, fpath, 0);

	while ((ch = uls_getch(sample_lex)) != ULS_NEXTCH_NONE) {
		if (ch == ULS_NEXTCH_QUOTE) {
			tok_id = uls_gettok(sample_lex);
			uls_printf(" str = '%s' (%d)\n", uls_lexeme_text(sample_lex), tok_id);
		} else {
			uls_printf(" ch = '%c'\n", ch);
		}
	}

	uls_destroy(sample_lex);

	return 0;
}
